from sys import argv
import init
from compile import *


def isInText(text: str) -> bool:
    g = 0
    t = 0
    for i in text:
        if i == "\\":
            g += 1
        if (i == "\"" or i == "'") and g % 2 == 0:
            t += 1
    return t % 2 == 1


# noinspection PyShadowingNames
def substitution(text: str, sub: list | tuple) -> str:
    i = 0
    j = 0
    text2 = ""
    for k in text:
        for sub1 in sub:
            if text[i:len(sub1[0]) + i] == sub1[0] and (not isInText(text[:i])) and (text[len(sub1[0]) + i] == "("):
                j += len(sub1[0])
                text2 += sub1[1]
                break
            # else:
            # print(text[i:len(sub1[0]) + i], sub1[0], not isInText(text[:i]))
        i += 1
        if j > 0:
            j -= 1
            continue
        text2 += k
    return text2


def getArgv(oldArgv: list, getArgv_: tuple, out: dict = None) -> dict:
    if out is None:
        out = {}
    j = 0
    for i in oldArgv:
        for k in getArgv_:
            if i == k:
                out[k] = oldArgv[j + 1]
                break
        j += 1
    return out


sub = (
    ("print", "print_"),
    ("@e", "ATe"),
    ("@a", "ATa"),
    ("@s", "ATs"),
    ("@p", "ATp"),
    ("@r", "ATr")
)
getArgv_ = ("-i", "-encoding", "-o")
argv = getArgv(argv, getArgv_, out={"-encoding": "utf-8"})

try:
    f = open(argv["-i"], "r", encoding=argv["-encoding"])
except KeyError:
    print("错误: 未指定待编译文件")
    exit(1)
fr = f.read()
f.close()
codes = substitution(fr, sub).split("\n")
fr = fr.split("\n")
out = []
i = 0
error = False

for code in codes:
    i += 1
    if code == "" or code[0] == "#":
        continue
    # print("正在解释 " + fr[i - 1] + " 中")
    try:
        _t = eval(code)
    except NameError as err:
        error = True
        err = str(err)
        _t = err.split("'")
        information = [_t[1]]
        del _t
        for j in sub:
            if j[1] == information[0]:
                information.append(j[0])
                break
        if len(information) == 2:
            print("错误: 找不到 " + information[1] + " 对应的解释函数. 在第" + str(i) + "行")
        else:
            print("错误: 语法错误(没有" + information[0] + "). 在第" + str(i) + "行")
        break
    except SyntaxError:
        try:
            exec(code)
            # print("无需翻译, 已执行")
            continue
        except Exception as err:
            error = True
            print("错误: " + str(err) + ". 在第" + str(i) + "行")
    except TypeError as err:
        error = True
        print("错误: " + str(err) + ". 在第" + str(i) + "行")
        break
    except Exception as err:
        error = True
        print("错误: " + str(err) + ". 在第" + str(i) + "行")
        break
    else:
        # print("翻译为 " + _t)
        out.append(_t)

if not error:
    f = open(argv["-o"], "w", encoding=argv["-encoding"])
    for i in out:
        f.write(i + "\n")
    f.close()
    print("翻译完成, 结果已写入 " + argv["-o"])
else:
    print("翻译因 " + argv["-i"] + " 出现错误而终止")
